from appserver import db_store
import traceback

"""
设备与传感器的中间表,第三张表,存储设备和传感器的外键id
"""

class DeviceWithSensor(db_store.Model):
    __tablename__ = "device_with_sensor"
    __main__ = "main"

    device_id = db_store.Column(db_store.Integer, db_store.ForeignKey('devices.id'), primary_key=True, nullable=False, comment=u"设备id")
    sensor_id = db_store.Column(db_store.Integer, db_store.ForeignKey('sensors.id'), primary_key=True, nullable=False, comment=u"传感器id")

    def __repr__(self):
        return "<DeviceWithSensor %d+%d>" %(self.device_id,self.sensor_id)
    """
    def save(self):
        try:
            db_store.session.add(self)
            db_store.session.commit()
            return True
        except Exception as e:
            db_store.session.rollback()
            print(e)
            return False
    
    def delete(self):
        try:
            db_store.session.delete(self)
            db_store.session.commit()
            return True
        except Exception as e:
            print(e)
            db_store.session.rollback()
            return False
    """

    def save(self):
        if self.device_id is None:
            print("DeviceWithSensor save error: device_id cannot be empty")
            return -1
        if self.sensor_id is None:
            print("DeviceWithSensor save error: sensor_id cannot be empty")
            return -2
        try:
            db_store.session.add(self)
            db_store.session.commit()
            return 0
        except:
            print("table projects_with_sensors write error:\n--------------------\n%s\n----------------------" % (
            traceback.format_exc()))
            db_store.session.rollback()
            return -3

    def delete(self):
        # id=self.id
        try:
            db_store.session.delete(self)
            db_store.session.commit()
            return 0
        except:
            print("DeviceWithSensor(id=%d) delete  error:\n-------------------\n%s\n----------------------"(id,
                                                                                                             traceback.format_exc()))
            db_store.session.rollback()
            return -1

    @staticmethod
    def add_sensors_to_device(device_id, sensor_ids):
        # 向指定用户添加一组按钮
        # 用法:
        #       role_id 角色id
        #       modules 模型id的列表
        for item in sensor_ids:
            sensor_connector = DeviceWithSensor()
            sensor_connector.device_id = device_id
            sensor_connector.sensor_id = item
            if sensor_connector.save() != 0:
                return -1
        return 0